﻿using CoreCms.Net.Caching.Configuration;
using EasyCaching.CSRedis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Silky.Core;
using System;
using System.Linq;

namespace CoreCms.Net.Caching
{
    public static class CacheServiceCollectionExtensions
    {
        public static IServiceCollection AddCacheService(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            var setting = EngineContext.Current.Configuration.
                                                    GetSection(CoreCmsDistributedCacheOptions.CoreCmsDistributedCache);
            services.AddOptions<CoreCmsDistributedCacheOptions>().Bind(setting);
            var op = setting.Get<CoreCmsDistributedCacheOptions>() ?? new CoreCmsDistributedCacheOptions();
            services.AddEasyCaching(option =>
            {
                option.UseInMemory("m1");
                if (op?.Redis != null && op.Redis.IsEnabled)
                {
                    option.UseCSRedis(config =>
                    {
                        config.DBConfig = new CSRedisDBOptions
                        {
                            ConnectionStrings = op.Redis.Configuration.Split(";").ToList()
                        };
                    }, "m2").WithJson("m2");
                }
            });

            return services;
        }

        public static IServiceCollection AddFreeRedisCahceService(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            var setting = EngineContext.Current.Configuration.
                                                    GetSection(RedisCaacheOptions.RedisCacheSettings);
            services.AddOptions<RedisCaacheOptions>().Bind(setting);
            var op = setting.Get<RedisCaacheOptions>();
            if(op == null)
            {
                return services;
            }
            FreeRedisClient.InitFreeRedisClient(op.RedisOptionsList);
            return services;
        }
    }
}